<template>
  <el-drawer size="1340px" @close="closeForm('')" :title="mode === 'add' ? '添加画像目标案件群':'编辑画像目标案件群'" :visible.sync="visible" :wrapperClosable="false">
    <el-form :model="form" :rules="rules" label-width="100px" class="drawerForm" ref="drawerForm">
      <el-form-item
          :label="portraitType === 'judicial_case'?'案件群名称':portraitType === 'criminal_suspect'?'嫌疑人群名称':'受害人群名称'"
          prop="name">
        <el-input
            class="input"
            v-model="form.name "
            placeholder="请输入名称"
            style="width: 330px"
        ></el-input>
      </el-form-item>
      <div class="attribute-wrapper">
        <div class="title-box">
          <span v-if="portraitType === 'judicial_case'">案件属性满足</span>
          <span v-if="portraitType === 'criminal_suspect'">嫌疑人属性满足</span>
          <span v-if="portraitType === 'victim'">受害人属性满足</span>
          <el-button @click="addItem" class="btn-add" type="text" size="small" icon="el-icon-circle-plus-outline">添加
          </el-button>
        </div>
        <div class="option-parent">
          <div class="option-list-line" @click="changeRuleType" v-if="form.ruleList?.length>1">且</div>
          <div style="flex: 1">
            <div class="option-list" v-for="(item,index) in form.ruleList" :key="index">
              <div class="option-box-line" v-if="item.children?.length>1">或</div>
              <div style="flex: 1">
                <div class="option-box clearfix" v-for="(ele,eleIndex) in item.children" :key="eleIndex">
                  <el-select
                      ref="select"
                      clearable
                      v-model="ele.item"
                      class="select1"
                      placeholder="请选择"
                      @change="changeCategoryId($event,ele)"
                  >
                    <el-option :value="op.infoField" :label="op.infoFieldDesc" v-for="(op,index) in selectList"
                               :key="index"></el-option>
                  </el-select>
                  <el-select
                      clearable
                      v-model="ele.calcType"
                      class="select1"
                      @change="ele.itemIsArry = null;ele.rangeValue1 = ''; ele.rangeValue2 = ''"
                      placeholder="请选择"
                      v-if="ele.options && ele.options.length !== 2"
                  >
                    <el-option :value="op.value" :label="op.label" v-for="(op,ox) in dictList" :key="ox"></el-option>
                  </el-select>
                  <el-select
                      clearable
                      v-model="ele.calcType"
                      class="select1"
                      @change="ele.itemIsArry = null;ele.rangeValue1 = ''; ele.rangeValue2 = ''"
                      placeholder="请选择"
                      v-if="ele.options && ele.options.length === 2"
                  >
                    <el-option :value="op.value" :label="op.label" v-for="(op,index) in ele.options"
                               :key="index"></el-option>
                  </el-select>
                  <template v-if="ele.calcType === 'between'">
                    <el-date-picker
                        type="datetime"
                        v-model="ele.rangeValue1"
                        value-format="yyyy-MM-dd HH:mm:ss"
                        placeholder="选择时间"
                        style="width:200px;"
                        v-if="['happened_time','birthday','suspect_birthday','victim_birthday'].includes(ele.item)"
                    ></el-date-picker>
                    <el-input
                        class="input topbut"
                        type="number"
                        v-model="ele.rangeValue1"
                        style="width:200px;"
                        v-else
                    ></el-input>
                    <span style="margin: 0 15px">与</span>
                    <el-date-picker
                        type="datetime"
                        v-model="ele.rangeValue2"
                        value-format="yyyy-MM-dd HH:mm:ss"
                        placeholder="选择时间"
                        style="width:200px;"
                        v-if="['happened_time','birthday','suspect_birthday','victim_birthday'].includes(ele.item)"
                    ></el-date-picker>
                    <el-input
                        class="input topbut"
                        type="number"
                        v-model="ele.rangeValue2"
                        style="width:200px;"
                        v-else
                    ></el-input>
                    <span style="margin-left: 15px">之间</span>
                  </template>
                  <template v-if="['eq','ne','in','notIn'].includes(ele.calcType)">
                    <el-select
                        clearable
                        collapse-tags
                        :multiple="['in','notIn'].includes(ele.calcType)"
                        v-model="ele.itemIsArry"
                        @change="changeItemIs($event,ele)"
                        class="select1"
                        placeholder="请选择"
                        v-if="ele.options?.length"
                    >
                      <el-option :value="op.value" :label="op.label" v-for="(op,index) in ele.options"
                                 :key="index"></el-option>
                    </el-select>
                    <template v-else>

                      <el-date-picker
                          type="date"
                          v-model="ele.itemIsArry"
                          @change="changeItemIs($event,ele)"
                          value-format="yyyy-MM-dd"
                          placeholder="选择日期"
                          style="width:220px;"
                          v-if="['birthday','suspect_birthday','victim_birthday'].includes(ele.item)"
                      >
                      </el-date-picker>
                      <el-date-picker
                          type="datetime"
                          v-model="ele.itemIsArry"
                          @change="changeItemIs($event,ele)"
                          value-format="yyyy-MM-dd HH:mm:ss"
                          placeholder="选择时间"
                          style="width:220px;"
                          v-else-if="['happened_time'].includes(ele.item)"
                      ></el-date-picker>
                      <el-input
                          class="input"
                          v-model="ele.itemIsArry"
                          @change="changeItemIs($event,ele)"
                          placeholder="请输入"
                          style="width:220px;"
                          v-else
                      ></el-input>
                    </template>
                  </template>
                  <span class="right" v-if="eleIndex === item.children.length - 1">
                      <el-button @click="delItem(index)" class="btn-del" size="small" icon="el-icon-delete" v-if="index > 0 && item.children.length === 1">删除且</el-button>
                      <el-button @click="delEle(item,eleIndex)" class="btn-del" size="small" icon="el-icon-delete" v-if="item.children.length > 1">删除或</el-button>
                      <el-button @click="addEle(item)" class="btn-add" size="small" icon="el-icon-circle-plus-outline">新增</el-button>
                    </span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </el-form>
    <div class="drawer-footer">
      <el-button @click="handleSubmit" :loading="btnLoading" size="small" class="btn plain-btn">
        保存
      </el-button>
      <el-button @click="handleChoose" size="small" class="btn btn2 default-btn" v-if="mode === 'add'">选择已建分群
      </el-button>
      <el-button @click="closeForm('')" size="small" class="btn default-btn">取消</el-button>
    </div>
    <choose-group-drawer
        :visible="chooseVisible"
        :portraitType="portraitType"
        @close="closeGroupDrawer"
    >
    </choose-group-drawer>
  </el-drawer>
</template>

<script>
import {sandbox, addRule} from '@/libs/util'
import drawer from '@/mixins/drawer.js'
import ChooseGroupDrawer from "./ChooseGroupDrawer";

const ruleList = [
  {
    calcType: null,
    children: [
      {
        calcType: null,
        id: null,
        item: '',
        itemDesc: '',
        itemIs: '',
        itemIsArry: null,
        logicalOperator: '或',
        orgId: null,
        pid: null,
        rangeValue1: null,
        rangeValue2: null,
        tagId: null,
      },
    ],
    id: null,
    item: '',
    itemDesc: '',
    itemIs: '',
    itemIsArry: null,
    logicalOperator: '且',
    orgId: null,
    pid: null,
    rangeValue1: null,
    rangeValue2: null,
    tagId: null,
  }
]

export default {
  name: "CaseGroupDrawer",
  components: {ChooseGroupDrawer},
  mixins: [drawer],
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    mode: {
      type: String,
      default: '',
    },
    portraitType: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      btnLoading: false,
      chooseVisible: false,
      form: sandbox({
        coveredNum: '',
        desc: '',
        name: '',
        portraitType: '',
        ruleNum: '',
        groupIds:[],
        ruleList: sandbox(ruleList),
      }),
      rules: {
        name: [{required: true, message: '必填项', trigger: 'blur'}],
        pid: [{required: true, message: '必填项', trigger: 'trigger'}],
      },
      selectList: [],
      dictList: [
        {
          value: 'between',
          label: '区间',
        },
        {
          value: 'eq',
          label: '等于',
        },
        {
          value: 'ne',
          label: '不等于',
        },
        {
          value: 'in',
          label: '包含',
        },
        {
          value: 'notIn',
          label: '不包含',
        },
        {
          value: 'isNotNull',
          label: '有值',
        },
        {
          value: 'isNull',
          label: '没有值',
        }
      ],
      ChooseGroupData: null,
      ChooseGroupDataStatic: null,
    }
  },
  methods: {
    AddRow() {
      let form = sandbox(this.form)
      form.portraitType = this.portraitType
      return this.$api.api_urcap_portrait_add({
        body: form,
        config: {showMsg: true}
      })
    },
    UpdateRow() {
      let form = sandbox(this.form)
      form.portraitType = this.portraitType
      return this.$api.api_urcap_portrait_edit({
        body: form,
        config: {showMsg: true}
      })
    },
    edit(row) {
      let data = sandbox(row)
      data.ruleList.forEach((item) => {
        item.children.forEach(async (ele) => {
          ele.options = await this.getOptions(ele.item)
          ele.itemIsArry = ele.itemIs
          if (['in', 'notIn'].includes(ele.calcType)) {
            ele.itemIsArry = ele.itemIs.split(',')
          }
        })
      })
      this.$nextTick(() => {
        Object.assign(this.form, data)
      })
    },
    async getOptions(value) {
      const selectRow = this.selectList.find(ele => ele.infoField === value)
      let options = []
      if (selectRow.infoFieldValue) {
        options = selectRow.infoFieldValue.replace(/,/g, '、').split('、').map(ele => {
          return {
            value: ele,
            label: ele
          }
        })
        if (options.length === 2) {
          options[0].value = 'yes'
          options[1].value = 'no'
        }
      }
      return options
    },
    handleSubmit() {
      this.$refs.drawerForm.validate(async valid => {
        if (valid) {
          if(this.validate(this.form)){
            this.$message({
              type: 'warning',
              message: '属性满足有必填项未填写'
            })
            return
          }
          console.log(JSON.stringify(this.ChooseGroupData) !== JSON.stringify(this.ChooseGroupDataStatic))
          console.log(this.ChooseGroupData)
          console.log(this.ChooseGroupDataStatic)
          if (JSON.stringify(this.ChooseGroupData) !== JSON.stringify(this.ChooseGroupDataStatic)) {
            await this.syncCon()
          }
          this.btnLoading = true
          ;(this.mode === 'add' ? this.AddRow() : this.UpdateRow())
              .then((res) => {
                this.closeForm(res.data)
              })
              .finally(() => {
                this.btnLoading = false
              })
        }
      })
    },
    validate(form){
      let result = false
      form.ruleList.forEach(ele=>{
        ele.children.forEach(item=>{
          if(!item.item){
            result = true
          }

          if(!item.calcType){
            result = true
          } else {
            if(item.calcType === 'between' && (!item.rangeValue1 || !item.rangeValue2)){
              result = true
            }
            if(item.calcType === 'eq' && !item.itemIsArry){
              result = true
            }
            if(item.calcType === 'ne' && !item.itemIsArry){
              result = true
            }
            if(item.calcType === 'in' && !item.itemIsArry?.length){
              result = true
            }
            if(item.calcType === 'notIn' && !item.itemIsArry?.length){
              result = true
            }
          }
        })
      })
      return result
    },
    async syncCon() {
      let name = ''
      switch (this.portraitType) {
        case 'judicial_case':
          name = '案件'
          break
        case 'criminal_suspect':
          name = '嫌疑人'
          break
        case 'victim':
          name = '受害人'
          break
      }
      await this.$confirm(`是否保存至${name}分群？`, '', {
        confirmButtonText: '保存',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        let form = sandbox(this.form)
        Object.assign(form, this.ChooseGroupData,{
          viewName: form.name,
          groupType: this.portraitType,
        })
        this.$api.api_urcap_group_edit({
          body: form,
        })
      }).catch(() => {
      })
    },
    handleChoose() {
      this.chooseVisible = true
    },
    async closeGroupDrawer(data) {
      if (data) {
        data.ruleList.forEach((item) => {
          item.children.forEach(async (ele) => {
            ele.options = await this.getOptions(ele.item)
            ele.itemIsArry = ele.itemIs
            if (['ne', 'notIn'].includes(ele.calcType)) {
              ele.itemIsArry = ele.itemIs.split(',')
            }
          })
        })
        this.$nextTick(() => {
          this.form.ruleList = data.ruleList
          this.form.coveredNum = data.peopleCoveredNum
          this.form.groupIds = [data.id]
          this.form.desc = data.remark
          this.form.name = data.viewName
          this.form.ruleNum = data.coveredNum
          this.ChooseGroupData = data
          this.ChooseGroupDataStatic = JSON.parse(JSON.stringify(data))
        })
      }
      this.chooseVisible = false
    },
    // 新增或
    addEle(item) {
      item.children.push(addRule('or'))
    },
    // 删除或
    delEle(item, eleIndex) {
      item.children.splice(eleIndex, 1)
    },
    // 删除且
    delItem(index){
      this.form.ruleList.splice(index,1)
    },
    // 新增且
    addItem() {
      this.form.ruleList.push(addRule('also'))
      console.log(this.form.ruleList)
    },
    changeRuleType(){

    },
    changeCategoryId(value, ele) {
      const selectRow = this.selectList.find(ele => ele.infoField === value)
      ele.options = []
      ele.itemIs = ''
      ele.calcType = ''
      if (selectRow.infoFieldValue) {
        ele.options = selectRow.infoFieldValue.replace(/,/g, '、').split('、').map(ele => {
          return {
            value: ele,
            label: ele
          }
        })
        if (ele.options.length === 2) {
          ele.options[0].value = 'yes'
          ele.options[1].value = 'no'
        }
      }
      this.$nextTick(() => {
        ele.itemDesc = this.$refs.select[0].selected.label
      })
    },

    // 格式化itemIs
    changeItemIs(val, ele) {
      if (typeof val === 'string') {
        ele.itemIs = val
      } else {
        ele.itemIs = val.join(',')
      }
    },

    // closeForm
    closeForm(isReload = '') {
      this.$emit('close', isReload)
      this.btnLoading = false
      this.$refs.groupForm && this.$refs.groupForm.resetFields()
      this.ChooseGroupData = null
      this.form = {
        coveredNum: '',
        desc: '',
        name: '',
        portraitType: '',
        ruleNum: '',
        ruleList: sandbox(ruleList),
        groupIds:[]
      }
    },
  },
  created() {
    this.$api.api_urcap_baseInfoAttrDict_queryList({
      body: {
        infoType: this.portraitType,
        PageIndex: 1,
        PageSize: 1000
      },
    }).then(res => {
      this.selectList = res.data
    })
  }
}
</script>

<style scoped>
.btn2 {
  color: #2774F4;
  border-color: #2774F4
}
</style>